package com.ch.dream.tools;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONObject;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface.OnCancelListener;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.Toast;

import com.ch.dream.R;
import com.ch.dream.asynctask.GetStoryModifyRequstAsyncTask;
import com.ch.dream.asynctask.GetStoryTypeRequstAsyncTask;
import com.ch.dream.base.BaseRequestAsyncTask.RequestServerListener;
import com.ch.dream.bean.RecommendtimeBean;
import com.ch.dream.bean.StorymodifyBean;
import com.ch.dream.bean.StorytypeBean;
import com.ch.dream.common.CommonData;
import com.ch.dream.common.CommonUserInfo;
import com.ch.dream.net.MyHttpAPI;

public class UtilTools {

	/**
	 *获取String类型的sp值
	 * @param context
	 * @param sp
	 * @param key
	 * @param value
	 */
	public static int getIntSharedPreferences(Context context,String sp,String key,int defValue){
		SharedPreferences sps = context.getSharedPreferences(sp, Context.MODE_PRIVATE);
		return sps.getInt(key, defValue);
	}
	
	/**
	 * 设置int类型的sp值
	 * @param context
	 * @param sp
	 * @param key
	 * @param value
	 */
	public static void setIntSharedPreferences(Context context,String sp,String key,int value){
		SharedPreferences sps = context.getSharedPreferences(sp, Context.MODE_PRIVATE);
		Editor editor = sps.edit();
		editor.putInt(key,value);
		editor.commit();
	}
	
	/**
	 * 设置String类型的sp值
	 * @param context
	 * @param sp
	 * @param key
	 * @param value
	 */
	public static void setStringSharedPreferences(Context context,String sp,String key,String value){
		SharedPreferences sps = context.getSharedPreferences(sp, Context.MODE_PRIVATE);
		Editor editor = sps.edit();
		editor.putString(key,value);
		editor.commit();
	}
	
	/**
	 * 清空sp
	 * @param context
	 * @param sp
	 * @param key
	 * @param value
	 */
	public static void clearSharedPreferences(Context context,String sp){
		SharedPreferences sps = context.getSharedPreferences(sp, Context.MODE_PRIVATE);
		Editor editor = sps.edit();
		editor.clear();
		editor.commit();
	}
	/**
	 * 请求故事类型,并绑定在spinner上
	 * 
	 */
	private static Spinner spStoryType;
	private static Spinner spStoryModify;
	public static void requestStoryType(Context activity,Spinner spStoryType){ 
		UtilTools.spStoryType = spStoryType;
		new GetStoryTypeRequstAsyncTask(activity, new RequestServerListener(){
			@Override
			public void onRequestServerEnd(Object result) {
				try{
					setStoryType((JSONArray)result);
					List<String> list =new ArrayList<String>();
					for(int i=0;i<CommonData.storyTypeList.size();i++){
						list.add(CommonData.storyTypeList.get(i).get("storyType").toString());
					}
					ArrayAdapter<String> sa = new ArrayAdapter<String>(CommonData.currentActivity,R.layout.spinner_item,list);
					sa.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
					if(UtilTools.spStoryType!=null){
						UtilTools.spStoryType.setAdapter(sa);
					}
				}
				catch (Exception e) {
					e.printStackTrace();
				}
			}
			
			@Override
			public void onRequestServerBegin() {
				
			}
		}).execute();
	}
	/**
	 * 设置故事类型list
	 * @param result
	 * @throws Exception
	 */
	public static void setStoryType(JSONArray result) throws Exception{
		CommonData.storyTypeList =new ArrayList<HashMap<String,Object>>();
		HashMap<String, Object> map =new HashMap<String, Object>();
		JSONArray jsonArray =result;
		for(int i=0;i<jsonArray.length();i++){
			JSONObject jsonObject = jsonArray.getJSONObject(i);
			StorytypeBean bean =new StorytypeBean();
			bean.setJsonObject(jsonObject);
			map =new HashMap<String, Object>();
			map.put("id", bean.getId());
			map.put("typeName", bean.getTypeName());
			map.put("fatherId", bean.getFatherId());
			CommonData.storyTypeList.add(map);
		}
	}
	
	/**
	 * 请求故事修饰词,并绑定在spinner上
	 * 
	 */
	private static String typeId;
	public static void requestStoryModify(Context activity,Spinner spStoryType,String typeId) throws Exception{ 
		UtilTools.spStoryModify = spStoryType;
		UtilTools.typeId = typeId;
		new GetStoryModifyRequstAsyncTask(activity, new RequestServerListener(){
			@Override
			public void onRequestServerEnd(Object result) {
				try{
					setStoryModify((JSONArray)result);
					ArrayAdapter<String> sa = new ArrayAdapter<String>(CommonData.currentActivity,R.layout.spinner_item,setStoryModifyType(UtilTools.typeId));
					sa.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
					if(UtilTools.spStoryModify!=null){
						UtilTools.spStoryModify.setAdapter(sa);
					}
				}
				catch (Exception e) {
					e.printStackTrace();
				}
			}
			
			@Override
			public void onRequestServerBegin() {
				
			}
		}).execute(new JSONObject().put("userId", CommonUserInfo.userId));
	}
	/**
	 * 设置故事修饰词list
	 * @param result
	 * @throws Exception
	 */
	public static void setStoryModify(JSONArray result) throws Exception{
		CommonData.storyModifyList =new ArrayList<HashMap<String,Object>>();
		HashMap<String, Object> map =new HashMap<String, Object>();
		JSONArray jsonArray =result;
		for(int i=0;i<jsonArray.length();i++){
			JSONObject jsonObject = jsonArray.getJSONObject(i);
			StorymodifyBean bean =new StorymodifyBean();
			bean.setJsonObject(jsonObject);
			map =new HashMap<String, Object>();
			map.put("id", bean.getId());
			map.put("modifyName", bean.getModifyName());
			map.put("modifyType", bean.getModifyType());
			CommonData.storyModifyList.add(map);
		}
	}
	/**
	 * 设置故事修饰符类型
	 * @param typeId
	 * @return
	 */
	public static List<String> setStoryModifyType(String typeId){
		List<String> list =new ArrayList<String>();
		CommonData.storyModifyIdList.clear();
		for(int i=0;i< CommonData.storyModifyList.size();i++){
			if(CommonData.storyModifyList.get(i).get("modifyType").toString().equals(typeId)){
				list.add(CommonData.storyModifyList.get(i).get("modifyName").toString());
				CommonData.storyModifyIdList.add(CommonData.storyModifyList.get(i).get("id").toString());
			}
		}
		return list;
	}
	/**
	 * 获取推荐列表
	 * @param jsonArray
	 * @return
	 */
	public static  List<HashMap<String, Object>> getRecommendList(JSONArray jsonArray){
		List<HashMap<String, Object>> result= new ArrayList<HashMap<String,Object>>();
		try{
			for(int i=0;i<jsonArray.length();i++){
				HashMap<String,Object> map = new HashMap<String, Object>();
				RecommendtimeBean bean = new RecommendtimeBean();
				bean.setJsonObject(jsonArray.getJSONObject(i));
				map.put("id",bean.getId());
				map.put("recommend",bean.getRecommend());
				map.put("sort",bean.getSort());
				result.add(map);
			}
		}catch (Exception e) {
			e.printStackTrace();
		}
		
		return result;
	}
	
	/**
	 * 判断非空及""字符
	 * @param src
	 * @return
	 */
	public static boolean isNotNullOrEmpty(String src){
		if(src == null){
			return false;
		}else if(src.trim().equals("")){
			return false;
		}else if(src.equals("null")){
			return false;
		}
		return true;
	}
	
	/**
	 * 安装应用
	 * @param context
	 * @param installName
	 */
	public static void setupApk(Context context,String installName) {
		String fileName = context.getApplicationContext().getFilesDir() + "/"
				+ installName;
		Uri uri = Uri.fromFile(new File(fileName));
		Intent intent = new Intent(Intent.ACTION_VIEW);
		intent.setDataAndType(uri, "application/vnd.android.package-archive");
		context.startActivity(intent);
	}
	
	/**
	 * 判断是否安装过某程序
	 * @param context
	 * @param packageName
	 * @return
	 */
	public static boolean isInstall(Context context,String packageName){
		PackageManager pckMan ;
		pckMan = context.getPackageManager();
		List<PackageInfo> packs = pckMan.getInstalledPackages(0);
		for(int i=0;i<packs.size();i++){
			PackageInfo p = packs.get(i);
			if(packageName.equals(p.packageName)){
				return true;
			}
		}
		return false;
	}
	/**
	 * 获取下载的handler
	 * @param context
	 * @param installFileName
	 * @param progressDialog
	 * @return
	 */
	public static Handler getDownLoadHandler(final Context context,final String installFileName,final ProgressDialog progressDialog){
		Handler handler =new Handler(){
			@Override
			public void handleMessage(Message msg) {
				switch (msg.what) {
				case 0:
					int result = msg.getData().getInt("len");
					progressDialog.setProgress(result);
					break;
					
				case 1:
					File file = new File(context.getFilesDir() + "/" + installFileName);
					if(file.exists())
						file.delete();
					progressDialog.dismiss();
					break;
					
				case 2:
					if(progressDialog.getProgress()<100){
						progressDialog.setProgress(0);
						for(int i =1;i<51;i++){
							progressDialog.setProgress(i*2);
							try{
								Thread.sleep(20);
							}catch (Exception e) {
								e.printStackTrace();
							}
						}
					}
					setupApk(context,installFileName);
					progressDialog.dismiss();
					break;
					
				case 3:
					Toast.makeText(context.getApplicationContext(), "抱歉，下载失败， 请稍后再试", Toast.LENGTH_SHORT).show();
					progressDialog.dismiss();
					break;
				}
			}
		};
		return handler;
	}
	
	public static boolean isStop = false;
	public static final int DOWNLOADING =0;
	public static final int DOWNLOADINTERRUPT =1;
	public static final int DOWNLOADOVER =2;
	public static final int DOWNLOADERROR =3;
	public static void downLoadWithHandlerFromUrl(Context context,String url,String fileName,Handler handler){
		DefaultHttpClient httpClient =new MyHttpAPI().getDefaultHttpClient();
		HttpGet request = new HttpGet(url);
		Message message = null;
		try {
			URL urlCon =new URL(url);
			HttpResponse response = httpClient.execute(request);
			HttpEntity entity = response.getEntity();
			InputStream inputStream =urlCon.openStream();
			int filesize = (int) entity.getContentLength();
			if (filesize > 0) {
				FileOutputStream os = context.openFileOutput(fileName, Context.MODE_WORLD_READABLE);
				int len = 0;
				int downloadfilesize = 0;
				byte[] data = new byte[1024];
				while ((len = inputStream.read(data)) != -1) {
					if(!isStop) {
						os.write(data, 0, len);
						downloadfilesize += len;
						message = new Message();
						message.what = DOWNLOADING;
						Bundle bundle = new Bundle();
						bundle.putInt("len", downloadfilesize * 100 / filesize);
						message.setData(bundle);
						handler.sendMessage(message);
					} else {
						os.close();
						message = new Message();
						message.what = DOWNLOADINTERRUPT;
						handler.sendMessage(message);
						return;
					}
				}
				os.close();
			}
			message = new Message();
			message.what = DOWNLOADOVER;
			handler.sendMessage(message);
		}catch (Exception e) {
			e.printStackTrace();
			message = new Message();
			message.what = DOWNLOADERROR;
			handler.sendMessage(message);
		}
	}
	
	public static ProgressDialog getDownProgress(Context context,String title,String message,OnCancelListener onCancelListener){
		ProgressDialog progressDialog = new ProgressDialog(context);
		progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
		progressDialog.setTitle(title);
		progressDialog.setMessage(message);
		progressDialog.setIndeterminate(false);
		progressDialog.setCancelable(true);
		progressDialog.setOnCancelListener(onCancelListener);
		progressDialog.setMax(100);
		return progressDialog;
	}
	
	
}
